import React, { Component } from 'react'
import {nanoid} from 'nanoid'

import Header from '../Header/Header'
import Main from '../Main/Main'
import './index.css'
import Footer from '../Footer/Footer'
export default class TodoList extends Component {
  state = {
    todos: [
        {
            id:nanoid(),
            title:'吃饭',
            isDone:true 
        },
        {
            id:nanoid(),
            title:'睡觉',
            isDone:true 
        },
        {
            id:nanoid(),
            title:'学习',
            isDone: false 
        }
    ]  
  }
  componentDidMount() {
    let todos = JSON.parse(localStorage.getItem('todos')) || []
    this.setState({
      todos
    })
  }
  componentDidUpdate() {
    localStorage.setItem('todos',JSON.stringify(this.state.todos))
  }
  // 添加方法
  addTodos(title) {
    console.log(title);
    let newtodo = {
      id: nanoid(),
      title,
      isDone: false
    } 
    this.setState({
      todos: [...this.state.todos, newtodo]
    })

  }
  // 删除方法
  deleteById(id) {
    if(!window.confirm('确定删除吗？')) return 
    console.log('fatherId',id);
    this.setState({
      todos: this.state.todos.filter(item => item.id !== id)
    })
    
  }
  // 切换选中状态
  changeChecked(id) {
    console.log('选中的id',id);
    this.setState({
      todos: this.state.todos.map(item => {
        if(item.id === id){
          item.isDone = !item.isDone
        }
        return item
      })
    })

  }
  // 选中全部状态
  checkAll(status) {
    console.log('选中的状态', status);
    
    this.setState({
      todos: this.state.todos.map(item =>{ 
        item.isDone = status
        return item
      })
    })
  }
  // 清除已完成的
  clearDone() {
    this.setState({
      todos: this.state.todos.filter(item => item.isDone === false)
    })
  }
  render() {
    let {todos} = this.state // 解构当前状态
    return (
     <>
         <div className="todo-container">
        <div className="todo-wrap">
          <Header addTodo={this.addTodos.bind(this)}></Header>
          <Main todos= {todos} deleteById={this.deleteById.bind(this)} changeChecked={this.changeChecked.bind(this)}></Main>
          <Footer todos={todos} checkAll={this.checkAll.bind(this)} clearDone={this.clearDone.bind(this)}></Footer>
        </div>
      </div>
     </>
    )
  }
 
}
